<?php
/**
 * Created by PhpStorm.
 * FileName: AppointmentModel.php
 * User: Administrator
 * Date: 2018/4/13
 * Time: 15:25
 */

namespace Admin\Model;

use Think\Model\RelationModel;

class AppointmentModel extends RelationModel {

    protected $tableName = 'appointment';

    protected $_link = array(
        'user' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'User',
            'foreign_key' => 'user_id',
            'mapping_key'  => 'id'
        ),

    );

    public function add($data) {
        $orgId = $data['org_id'];
        $userIds = $data['user_id'];
        $orderTime = $data['order_time'];
        $weekAll = $data['week_all'];
        $timeRange = $data['time_range'];
        $nums = $data['nums'];

        if ($weekAll) {
            //一周内相同业务逻辑
            $curWeek = getCurWeek($orderTime);
            $weekList = getWeekRange($curWeek['start'],$curWeek['end']);
            //忽略历史预约
            $start = max(strtotime($curWeek['start']),strtotime(date('Y-m-d')));
            //忽略周六周日
            $end = date('Y-m-d',strtotime($curWeek['end'].' - 2 day'));
            $delWhere = array(
                'user_id' => array('in',$userIds),
                'order_time' => array('exp','>='.$start.' and order_time <='.$end)
            );
            $this->where($delWhere)->delete();
            $dataList = array();
            foreach ($userIds as $userId) {
                foreach ($weekList as $week) {
                    //忽略历史预约
                    if (strtotime($week['fullDay']) < $start || strtotime($week['fullDay']) > strtotime($end)) {
                        continue;
                    }
                    $data = array(
                        'user_id' => $userId,
                        'org_id' => $orgId,
                        'order_time' => strtotime($week['fullDay']),
                        'time_range' => json_encode((object)$timeRange),
                        'create_time' => time(),
                        'nums' => $nums
                    );
                    $dataList[] = $data;
                }
            }
        } else {
            $delWhere = array(
                'user_id' => array('in',$userIds),
                'order_time' => strtotime($orderTime)
            );
            $this->where($delWhere)->delete();
            $dataList = array();
            foreach ($userIds as $userId) {
                $data = array(
                    'user_id' => $userId,
                    'org_id' => $orgId,
                    'order_time' => strtotime($orderTime),
                    'time_range' => json_encode((object)$timeRange),
                    'create_time' => time(),
                    'nums' => $nums
                );
                $dataList[] = $data;
            }
        }

        return $this->addAll($dataList);
    }

    public function getList($curTime) {
        $where = array(
            'FROM_UNIXTIME(order_time,\'%Y-%m-%d\')' => $curTime
        );
        $dataList = $this->relation(array('user'))->where($where)->select();
        $result = array();
        foreach ($dataList as $data) {
            $timeRange = json_decode($data['time_range'],true);
            foreach ($timeRange as $time) {
                $result[date('Y-m-d',$data['order_time'])][$time][$data['org_id']][] = $data;
            }
        }
        return $result;
    }

    public function del($id,$time) {
        $where = array('id' => $id);
        $row = $this->where($where)->find();
        $timeRange = json_decode($row['time_range'],true);
        foreach($timeRange as $k => $v){
            if($v == $time){
                unset($timeRange[$k]);
            }
        }
        //删除后，数组如果不为空，time_range作更新处理
        if ($timeRange) {
            return $this->where($where)->save(array('time_range' => json_encode((object)$timeRange)));
        }
        return $this->where($where)->delete();
    }

    /**
     * 检查指定的时间段是否可以接受预约
     * @param $orgId 部门id
     * @param $userId 服务人员id
     * @param $orderTime 预约日期
     * @param $timeRange 预约时间段
     * @return bool true 可以接受预约 | false 不能接受预约
     */
    public function isAvailable($orgId,$userId,$orderTime,$timeRange) {
        $where = array(
            'org_id' => $orgId,
            'user_id' => $userId,
            'order_time' => strtotime($orderTime)
        );
        $row = $this->where($where)->find();
        if ($row) {
            $timeRanges = json_decode($row['time_range'],true);
            if ($timeRanges) {
                return in_array($timeRange,$timeRanges) ? true : false;
            }
            return false;
        }
        return false;
    }

    /**
     * 获取每个用户被分配的预约时间段
     * @param $orgId 部门id
     * @param $orderTime 日期
     * @return array
     */
    public function getAppoints($orgId,$orderTime) {
        $where = array(
            'org_id' => $orgId,
            'order_time' => strtotime($orderTime)
        );
        $appointments = $this->where($where)->field('user_id,time_range,nums')->select();

        $availableTimeRange = array();
        foreach ($appointments as $appointment) {
            $timeRange = json_decode($appointment['time_range'],true);
            $availableTimeRange[$appointment['user_id']]['time_range'] = $timeRange;
            $availableTimeRange[$appointment['user_id']]['nums'] = $appointment['nums'];
        }
        return $availableTimeRange;
    }

    /**
     * 获取每个部门指定日期的预约总数
     * @param $orgId
     * @param $orderTime
     * @return mixed
     */
    public function getTotalNums($orgId,$orderTime) {
        $where = array(
            'org_id' => $orgId,
            'order_time' => strtotime($orderTime)
        );
        $total = $this->where($where)->sum('nums');
        return $total;
    }
}